package edu.sias.controller;

import edu.sias.pojo.Category;
import edu.sias.pojo.Post;
import edu.sias.service.CategoryService;
import edu.sias.service.SearchService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

//检索操作的控制层，控制前后端的交互
//urlPatterns： 用于映射前端请求路劲
@WebServlet(urlPatterns = {"/search"})
public class SearchServlet extends HttpServlet {
    /**
     *
     * @param request   代表用户发起的请求，里面包含请求的相关信息
     * @param response  代表服务端返回前端的响应，包含响应给前端的数据
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //获取文章类别信息，将其保存到session中，便于共享展示
        CategoryService categoryService
                = new CategoryService();
        List<Category> list
                = categoryService.categoryList();
        request.getSession()
                .setAttribute("categories",list);

        //获取前端发送的数据
        String keyMsg = request.getParameter("keyMsg");
        System.out.println("keyMsg = " + keyMsg);
        //调用检索业务层操作，获取处理好的数据
        SearchService searchService = new SearchService();
        List<Post> posts = searchService.getMsgInfo(keyMsg);

        //返回数据给用户
        request.setAttribute("posts",posts);
        //转发到showMsg，同时数据在request中
        request.getRequestDispatcher("showMsg.jsp").forward(request,response);
    }
}
